/*
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * DMGIS. You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with DMGIS.
 *
 */
package com.dmgis.qxfw.dataservice.businessservice.yyyj.service.Impl;

import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.disweather_moni_condition;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.disweather_moni_info;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.warning;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.base_product;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ActualElemQuery;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.MsgMediumSmallScale;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.ActualData;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.TownshipForecastKey;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.cdyj.service.IEmergencyService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;


@Service("Emergency")
public class EmergencyService implements IEmergencyService {

    ProcessRequestController procon = new ProcessRequestController();

    @Resource
    private ITransformService transformService;

    @Override
    public List<special_srv_station> getAnjianByNameandId(String staName, String staId) {
        // TODO Auto-generated method stub
        List<special_srv_station> newDate = new ArrayList<special_srv_station>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        int whereCount = 0;
        StringBuilder strWhere = new StringBuilder();
        if (!StringUtil.IsNullOrEmpty(staName)) {
            whereCount++;
            strWhere.append("stationname like '%" + staName + "%'");
        }
        if (!StringUtil.IsNullOrEmpty(staId)) {
            strWhere.append(" and stationid like '%" + staId + "%'");
        }
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        strWhere.append(String.format(" and city like '%s%%'", DbConfig.CITY));
        selectRequest.setParam(strWhere.toString());
        try {
            selectParam.put("method", "special_srv_station");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            newDate = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<special_srv_station>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
        }
        return newDate;
    }

    @Override
    public List<township_forecasttemp> getAnjianFcst(String r, String lon, String lat) {
        TownshipForecastKey newDate = new TownshipForecastKey();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String[] columns = new String[]{"to_char(datechar, 'yyyy-MM-dd HH24:MI:SS') as dateChar", "timechar"};
        selectRequest.setColumns(columns);
        selectRequest.setSort(new String[]{"datechar desc", "timechar desc"});
        selectRequest.setLimit(1);
        try {
            selectParam.put("method", "township_forecast");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            if (!message.equals("[]")) {
                newDate = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<TownshipForecastKey>>() {
                }).get(0);
            }
        } catch (Exception e) {
            // TODO: handle exception
            newDate.setDateChar(DateTime.now().toDate());
            newDate.setNTimes(DateTime.now().GetHour() >= 8 && DateTime.now().GetHour() < 20 ? 8 : 20);
        }
        List<township_forecasttemp> resultList = new ArrayList<township_forecasttemp>();
        if (newDate.getTimeChar() != null) {
            selectParam = new HashMap<String, String>();
            selectRequest = new RequestDataBySelect();
            List<String> column = new ArrayList<String>();
            column.add("timechar");
            column.add("ntimes");
            column.add("stationid");
            column.add("StationName");
            column.add("longitude");
            column.add("latitude");
            column.add("CAST(replace(cast(humid AS VARCHAR),'-65535','99999') as numeric(18,1)) as humid");
            column.add("to_char(datechar, 'yyyy-MM-dd HH24:MI:SS') as dateChar");
            column.add("NTimes");
            column.add("weather1");
            column.add("CAST(replace(cast(maxtemp AS VARCHAR),'-65535','99999') as numeric(18,1)) as maxtemp");
            column.add("CAST(replace(cast(minTemp AS VARCHAR),'-65535','99999') as numeric(18,1)) as minTemp");
            column.add("winds");
            column.add("windd");
            column.add("rain");
            selectRequest.setColumns(column.toArray(new String[column.size()]));
            // 拼接where字段
            StringBuilder strWhere = new StringBuilder();
            if (newDate.getDateChar() != null) {
                strWhere.append(String.format(" and datechar='%tF'", newDate.getDateChar()));
            }
            if (!StringUtil.IsNullOrEmpty(newDate.getTimeChar())) {
                strWhere.append(String.format(" and timechar='%s'", newDate.getTimeChar()));
            }
            strWhere.append(String.format(" and ntimes<='%d' and ntimes >'%d'", 24, 0));
            if (!StringUtil.IsNullOrEmpty(strWhere.toString())) {
                strWhere = strWhere.replace(0, 4, "");
            }
            strWhere.append(String.format(" and city like '%s%%'", DbConfig.CITY));
            selectRequest.setParam(strWhere.toString());
            selectRequest.setSort(new String[]{"datechar desc", "StationID ASC", "NTimes ASC"});
            try {
                if (DateTime.UserMainDataTable(newDate.getDateChar(), DbConfig.CACHEDAYS)) {
                    selectParam.put("method", "township_forecast");
                } else {
                    selectParam.put("method", "township_forecast");
                }
                selectParam.put("sqlType", "select");
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message = procon.processRequest(selectParam);
                resultList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<township_forecasttemp>>() {
                });
            } catch (Exception e) {
                // TODO: handle exception
                System.err.println(e.getStackTrace());
            }
        }
        return resultList;
    }

    @Override
    public List<MsgMediumSmallScale> getAnjianSKInfo(ActualElemQuery elemQuery) {
        List<MsgMediumSmallScale> dataList = new ArrayList<MsgMediumSmallScale>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String element = elemQuery.getElement();
        Date startDate = elemQuery.getStartDate();
        Date endDate = elemQuery.getEndDate();
        String type = "";
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (startDate != null) {
            whereCount++;
            strWhere.append(String.format("observTime >='%tF %tT'", startDate, startDate));
        }
        if (endDate != null) {
            strWhere.append(String.format(" and observTime <='%tF %tT'", endDate, endDate));
        }
        strWhere.append(String.format(" and city like '" + DbConfig.CITY + "%'"));
        // 获取查询字段
        List<String> columns = new ArrayList<String>();
        columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
        columns.add("StationName");
        columns.add("longitude");
        columns.add("latitude");
        columns.add("sum(rain) as rain");
        selectRequest.setSort(new String[]{"rain desc"});
        strWhere.append(" and rain <> -65535");
        if (element.contains("max")) {
            type = "max";
        } else if (element.contains("min")) {
            type = "min";
        } else {
            type = "sum";
        }
        // 温度统计
        if (type != null && type.equals("sum") || type.equals("avg") || type.equals("min") || type.equals("max")) {
            columns.add("cast(" + type + "(cast(DryBulbTemp as numeric(18,1))) as FLOAT) as DryBulbTemp");
            strWhere.append(" and DryBulbTemp <> -65535");
            selectRequest.setSort(new String[]{"DryBulbTemp desc"});
        }
        // 风速
        columns.add("max(InstantWindV) as InstantWindV");
        strWhere.append(" and InstantWindV <> -65535");
        selectRequest.setSort(new String[]{"InstantWindV desc"});

        // 风向
        columns.add("max(InstantWindD) as InstantWindD");
        strWhere.append(" and InstantWindD <> -65535");
        selectRequest.setSort(new String[]{"InstantWindD desc"});

        // 本站气压
        columns.add("avg(StationPress) as StationPress");
        strWhere.append(" and StationPress <> -65535");
        selectRequest.setSort(new String[]{"StationPress desc"});
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            selectParam.put("method", "msgmediumsmallscale");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<MsgMediumSmallScale>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
        }

        return dataList;
    }


    @Override
    public List<base_product> getYjWord() {
        List<base_product> listData = new ArrayList<base_product>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<String> columns = new ArrayList<String>();
        columns.add("id");
        columns.add("forecasttime");
        columns.add("productname");
        columns.add("producttype");
        columns.add("maketime");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        selectRequest.setParam("producttype='应急服务'");
        selectRequest.setSort(new String[]{"maketime desc"});
        selectRequest.setLimit(2);
        try {
            selectParam.put("method", "base_product");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<base_product>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        return listData;
    }


    @Override
    public List<disweather_moni_condition> InitdisasterType() {
        List<disweather_moni_condition> types = new ArrayList<>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<String> columns = new ArrayList<String>();
        columns.add("disweather_name");
        columns.add("disweather_condition");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        try {
            selectParam.put("method", "disweather_moni_condition");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            types = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<disweather_moni_condition>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        return types;
    }

    @Override
    public List<disweather_moni_info> GetdisasterInfo(disweather_moni_info info) {
        List<disweather_moni_info> resultList = new ArrayList<disweather_moni_info>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        List<String> columns = new ArrayList<String>();
        columns.add("disweather_name");
        columns.add("happen_time");
        columns.add("count(1)");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        int whereCount = 0;
        if (!StringUtil.IsNullOrEmpty(info.getStartDate())) {
            strWhere.append(String.format("and happen_time>='%s'", info.getStartDate()));
        }
        if (!StringUtil.IsNullOrEmpty(info.getEndDate())) {
            strWhere.append(String.format(" and happen_time<='%s'", info.getEndDate()));
        }
        if (info.getDisweather_name() != null) {
            if (!info.getDisweather_name().equals("全部")) {
                strWhere.append(String.format(" and  disweather_name='%s'", info.getDisweather_name()));
            }
        }

        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }

        selectRequest.setParam(strWhere.toString());
        selectRequest.setSort(new String[]{"happen_time desc"});
        try {
            selectParam.put("method", "disweather_moni_info");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            resultList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<disweather_moni_info>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }


        List<disweather_moni_info> disweather_moni_infos = new ArrayList<disweather_moni_info>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (resultList != null && resultList.size() > 0) {
            for (disweather_moni_info dop : resultList) {
                disweather_moni_info dis = new disweather_moni_info();
                dis.setDisweather_name(dop.getDisweather_name());
                dis.setTime(format.format(dop.getHappen_time()));
                dis.setHappen_time(dop.getHappen_time());
                dis.setDate(format1.format(dop.getHappen_time()));
                disweather_moni_infos.add(dis);
            }
        }


        return disweather_moni_infos;


    }

    @Override
    public List<disweather_moni_info> ShowDisaster(String time, String type) {
        List<disweather_moni_info> resultList = new ArrayList<disweather_moni_info>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        selectRequest.setParam(String.format("happen_time='%s' and  disweather_name='%s'", time, type));
        try {
            selectParam.put("method", "disweather_moni_info");
            selectParam.put("sqlType", "select");
            selectParam.put("advCode", DbConfig.advCode);
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            resultList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<disweather_moni_info>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }

        List<smallscale_station> stalist = new ArrayList<smallscale_station>();
        Map<String, String> selectParam1 = new HashMap<String, String>();
        RequestDataBySelect selectRequest1 = new RequestDataBySelect();
        List<String> columns1 = new ArrayList<String>();
        columns1.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
        columns1.add("stationname");
        columns1.add("longitude");
        columns1.add("latitude");
        selectRequest1.setColumns(columns1.toArray(new String[columns1.size()]));
        try {
            selectParam1.put("method", "smallscale_station");
            selectParam1.put("sqlType", "select");
            selectParam1.put("param", JsonUtil.object2Json(selectRequest1));
            String message = procon.processRequest(selectParam1);
            stalist = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<smallscale_station>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
        }
        Map<String, smallscale_station> map = new HashMap<String, smallscale_station>();
        for (smallscale_station station : stalist) {
            map.put(station.getStationid(), station);
        }
        List<disweather_moni_info> disweather_moni_infos = new ArrayList<disweather_moni_info>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        if (resultList != null && resultList.size() > 0) {
            for (disweather_moni_info dop : resultList) {
                disweather_moni_info dis = new disweather_moni_info();
                for (String key : map.keySet()) {  //keySet获取map集合key的集合  然后在遍历key即可
                    if (key.equals(dop.getStationid())) {
                        dis.setName(map.get(key).getStationname());
                        dis.setLon(map.get(key).getLongitude());
                        dis.setLat(map.get(key).getLatitude());
                    }
                }
                dis.setDisweather_name(dop.getDisweather_name());
                dis.setTime(format.format(dop.getHappen_time()));
                dis.setHappen_time(dop.getHappen_time());
                dis.setStationid(dop.getStationid());
                dis.setDisweather_result(dop.getDisweather_result());
                disweather_moni_infos.add(dis);
            }
        }


        return disweather_moni_infos;
    }


    @Override
    public List<ActualData> qxElementQuery(String startDate, String endDate, String stationid, String element, String chartType) {
        // TODO 气象要素统计
        List<ActualData> resultList = new ArrayList<>();
        List<msgmediumsmallscale> dataList = new ArrayList<>();
        Map<String, String> selectParam = new HashMap<>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (startDate != null) {
            whereCount++;
            strWhere.append(String.format("observTime >='%s'", startDate));
        }
        if (endDate != null) {
            strWhere.append(String.format(" and observTime <='%s'", endDate));
        }
        if (stationid != null && stationid.length() > 0) {
            strWhere.append(" and stationId in (");
            String tempString = "";
            tempString += String.format("'%s',", stationid);
            strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
        }
        // 获取查询字段
        List<String> columns = new ArrayList<String>();
        columns.add("stationid");// pg字段大小写不敏感的话，默认全部转换成小写模式
        columns.add("stationname");
        columns.add("longitude");
        columns.add("latitude");
        if (element != null && element.equals("rain")) {
            // 表格统计
            if (chartType != null && (chartType.equals("spline") || chartType.equals("column"))) {
                columns.add("observtime");
                columns.add("rain");
                strWhere.append(" and rain <> -65535");
                selectRequest.setSort(new String[]{"observtime"});
            }
        }
        if (element != null && element.equals("temp")) {
            // 表格统计
            if (chartType != null && (chartType.equals("spline") || chartType.equals("column"))) {
                columns.add("observtime");
                columns.add("DryBulbTemp");
                strWhere.append(" and DryBulbTemp <> -65535");
                selectRequest.setSort(new String[]{"observtime"});
            }
        }
        if (element != null && element.equals("winds")) {
            // 表格统计
            if (chartType != null && (chartType.equals("spline") || chartType.equals("column"))) {
                columns.add("observtime");
                columns.add("InstantWindV");
                strWhere.append(" and InstantWindV <> -65535");
                selectRequest.setSort(new String[]{"observtime"});
            }
        }
        if (element != null && element.equals("humid")) {
            // 表格统计
            if (chartType != null && (chartType.equals("spline") || chartType.equals("column"))) {
                columns.add("observtime");
                columns.add("RelHumidity");
                strWhere.append(" and RelHumidity <> -65535");
                selectRequest.setSort(new String[]{"observtime"});
            }
        }
        if (element != null && element.equals("pressure")) {
            // 表格统计
            if (chartType != null && (chartType.equals("spline") || chartType.equals("column"))) {
                columns.add("observtime");
                columns.add("StationPress");
                strWhere.append(" and StationPress <> -65535");
                selectRequest.setSort(new String[]{"observtime"});
            }
        }
        if (element != null && element.equals("visibility")) {
            // 表格统计
            if (chartType != null && (chartType.equals("spline") || chartType.equals("column"))) {
                columns.add("observtime");
                columns.add("visibility");
                strWhere.append(" and visibility <> -65535");
                selectRequest.setSort(new String[]{"observtime"});
            }
        }
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            selectParam.put("method", "msgmediumsmallscale");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<msgmediumsmallscale>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
        }
        // 赋值
        try {
            WebCtrlData webCtrlData = new WebCtrlData();
            if (dataList.size() > 0) {
                for (msgmediumsmallscale data : dataList) {
                    ActualData actualData = new ActualData();
                    actualData.setStationId(data.getStationid().trim());
                    actualData.setStationName(data.getStationname().trim());
                    actualData.setLon(data.getLongitude());
                    actualData.setLat(data.getLatitude());
                    DmMapPoint dt = transformService.LonLatConvertToLambert(data.getLongitude(), data.getLatitude());
                    actualData.setX(dt.x);
                    actualData.setY(dt.y);
                    switch (element) {
                        case "rain":
                            actualData.setRain(Double.parseDouble(String.format("%.1f", data.getRain())));
                            break;
                        case "temp":
                            actualData.setTemp(Double.parseDouble(String.format("%.1f", data.getDrybulbtemp())));
                            break;
                        case "humid":
                            actualData.setHumid(Double.parseDouble(String.format("%d", data.getRelhumidity())));
                            break;
                        case "winds":
                            actualData.setWinds(Double.parseDouble(String.format("%.1f", data.getInstantwindv())));
                            break;
                        case "pressure":
                            actualData.setPressure(Double.parseDouble(String.format("%.1f", data.getStationpress())));
                            break;
                        case "visibility":
                            actualData.setVisibility(data.getVisibility());
                            break;
                        default:
                            break;
                    }
                    actualData.setDateTime(data.getObservtime());
                    resultList.add(actualData);
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return resultList;
    }

    public List<water_station> WeaterStation() {
        List<water_station> list = new ArrayList<water_station>();
        Map<String, String> selectParam1 = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        selectRequest.setParam(" stlc like '%" + DbConfig.CITY + "%' and locality like '%水文%' ");
        try {
            selectParam1.put("method", "water_station");
            selectParam1.put("sqlType", "select");
            selectParam1.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam1);
            list = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<water_station>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
        }
        return list;
    }

    public Date initWeater() {
        HashMap<String, String> selectParam = new HashMap<>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        Date date = new Date();
        String[] columns = new String[]{"to_char(latestobservetime, 'yyyy-MM-dd HH24:MI:SS') as latestobservetime"};
        selectRequest.setColumns(columns);
        selectRequest.setParam(String.format("location like '%s%%'", DbConfig.CITY));
        selectRequest.setSort(new String[]{"latestobservetime desc"});
        selectRequest.setLimit(1);
        try {
            selectParam.put("method", "water");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            date = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<water>>() {
            }).get(0).getLatestobservetime();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return date;
    }

    public List<water> Water(List<String> station, String date) {
        List<water> waters = new ArrayList<water>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (date != null) {
            strWhere.append(String.format(" and time='%s'", date));
        }
        if (station != null && station.size() > 0) {
            strWhere.append(" and stnm in (");
            String tempString = "";
            for (String stations : station) {
                tempString += String.format("'%s',", stations);
            }
            strWhere.append(tempString.substring(0, tempString.length() - 1) + ")");
        }
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            selectParam.put("method", "water");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            waters = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<water>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        return waters;
    }

    public List<water> WaterChart(String startDate, String endDate, String stationname) {
        List<ActualData> resultList = new ArrayList<ActualData>();
        List<water> dataList = new ArrayList<water>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        // 获取查询字段
        List<String> columns = new ArrayList<String>();
        columns.add("stationid");
        columns.add("stationname");
        columns.add("smallscalewaterstatus");
        columns.add("latestobservetime");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));

        // 拼接where字段
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (startDate != null) {
            whereCount++;
            strWhere.append(String.format("latestobservetime >='%s'", startDate));
        }
        if (endDate != null) {
            strWhere.append(String.format(" and latestobservetime <='%s'", endDate));
        }
        if (stationname != null) {
            strWhere.append(String.format(" and stationname='%s'", stationname));
        }

        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        try {
            selectParam.put("method", "water");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            dataList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<water>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println(e.getStackTrace());
        }
        return dataList;
    }

    public Date initFireTime() {
        satellitenephoram3 newDate = new satellitenephoram3();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        String[] columns = new String[]{"to_char(datechar, 'yyyy-MM-dd HH24:MI:SS') as datechar"};
        selectRequest.setColumns(columns);
        selectRequest.setSort(new String[]{"datechar desc"});
        selectRequest.setLimit(1);
        try {
            selectParam.put("method", "satellitenephoram3");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            newDate = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<satellitenephoram3>>() {
            }).get(0);
        } catch (Exception e) {
            // TODO: handle exception
            newDate.setDatechar(DateTime.now().toDate());
        }
        return newDate.getDatechar();
    }


    @Override
    public List<satellitenephoram3> getFirepoint(String startDate, String endDate) {
        List<satellitenephoram3> listData = new ArrayList<satellitenephoram3>();
        List<satellitenephoram3> resultList = new ArrayList<satellitenephoram3>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        StringBuilder strWhere = new StringBuilder();
        int whereCount = 0;
        if (startDate != null) {
            whereCount++;
            strWhere.append(String.format("datechar>='%s'", startDate));
        }
        if (endDate != null) {
            strWhere.append(String.format(" and datechar<='%s'", endDate));
        }
        if (whereCount == 0 && !StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        selectRequest.setSort(new String[]{"datechar desc"});
        try {
            selectParam.put("method", "satellitenephoram3");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            listData = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<satellitenephoram3>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if (listData != null && listData.size() > 0) {
            for (satellitenephoram3 em : listData) {
                satellitenephoram3 sate = new satellitenephoram3();
                sate.setDatechar(em.getDatechar());
                sate.setCoordinates(em.getCoordinates());
                sate.setDatayear(em.getDatayear());
                sate.setTimechar(em.getTimechar());
                sate.setYttype(em.getYttype());
                sate.setTime(sdf.format(em.getDatechar()));
                resultList.add(sate);
            }
        }
        return resultList;
    }


    @Override
    public List<msgmediumsmallscale> qxElementQuery(String startDate, String endDate) {
        List<msgmediumsmallscale> resultList = new ArrayList<msgmediumsmallscale>();
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<String> columns = new ArrayList<String>();
        columns.add("distinct stationname");
        columns.add("stationid");
        columns.add("longitude");
        columns.add("latitude");
        columns.add("sum(rain) as rain");
        columns.add("cast(avg(cast(DryBulbTemp as numeric(18,1))) as FLOAT) as DryBulbTemp");
        columns.add("avg(InstantWindV) as InstantWindV");
        columns.add("cast(avg(RelHumidity) as integer) as RelHumidity");
        columns.add("avg(StationPress) as StationPress");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        StringBuilder strWhere = new StringBuilder();
        if (!StringUtil.IsNullOrEmpty(startDate)) {
            strWhere.append(String.format("observtime>='%s'", startDate));
        }
        if (!StringUtil.IsNullOrEmpty(endDate)) {
            strWhere.append(String.format(" and observtime<='%s'", endDate));
        }
        selectRequest.setParam(strWhere.toString());
        selectRequest.setSort(new String[]{"rain desc"});
        try {
            selectParam.put("method", "msgmediumsmallscale");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            resultList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<msgmediumsmallscale>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        return resultList;
    }

    @Override
    public List<warning> getWarningInfo(String startDate, String endDate, int id) {
        // TODO 预警信号表
        //查询关注预警区
        Map<String, String> selectParam = new HashMap<String, String>();
        RequestDataBySelect selectRequest = new RequestDataBySelect();
        List<warning> resultList = new ArrayList<warning>();
        List<String> columns = new ArrayList<String>();
        columns.add("id");
        columns.add("Area");
        columns.add("Type");
        columns.add("Color");
        columns.add("County");
        columns.add("Standard");
        columns.add("DefenseGuide");
        columns.add("to_char(AnnouncedTime, 'yyyy-MM-dd HH24:MI:SS') as AnnouncedTime");
        columns.add("pos");
        columns.add("bFree");
        columns.add("y2path");
        columns.add("description");
        selectRequest.setColumns(columns.toArray(new String[columns.size()]));
        StringBuilder strWhere = new StringBuilder();
        if (!StringUtil.IsNullOrEmpty(startDate)) {
            strWhere.append(String.format(" and AnnouncedTime>='%s'", startDate));
        }
        if (!StringUtil.IsNullOrEmpty(endDate)) {
            strWhere.append(String.format(" and AnnouncedTime<='%s'", endDate));
        }
        strWhere.append(String.format(" and city like '" + DbConfig.CITY + "'"));
        strWhere.append(String.format(" and bfree=0"));
        if (id > 0) {
            strWhere.append(String.format(" and id=%d", id));
        }
        if (!StringUtil.IsNullOrEmpty(strWhere.toString())) {
            strWhere = strWhere.replace(0, 4, "");
        }
        selectRequest.setParam(strWhere.toString());
        selectRequest.setSort(new String[]{"AnnouncedTime desc"});
        try {
            selectParam.put("method", "warn_signal_info");
            selectParam.put("sqlType", "select");
            selectParam.put("param", JsonUtil.object2Json(selectRequest));
            String message = procon.processRequest(selectParam);
            resultList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<warning>>() {
            });
        } catch (Exception e) {
            // TODO: handle exception
        }
        return resultList;
    }


}
